package com.epic.followup.controller.wechat;

import static com.epic.followup.util.HTTPsUtils.get;

import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epic.followup.conf.WeChatConfig;
import com.epic.followup.model.app.AppPatientModel;
import com.epic.followup.service.wechat.WechatPatientService;
import com.epic.followup.temporary.DealMessageResponse;
import com.epic.followup.temporary.followup2.CodeRequest;
import com.epic.followup.temporary.wechat.patient.WechatInformationRequest;
import com.epic.followup.temporary.wechat.patient.WechatInformationResponse;
import com.epic.followup.temporary.wechat.patient.WechatLoginbyCodeRequest;
import com.epic.followup.temporary.wechat.patient.WechatLoginbyCodeResponse;
import com.epic.followup.temporary.wechat.patient.WechatLoginbyPasswordRequest;
import com.epic.followup.temporary.wechat.patient.WechatRegisterRequest;
import com.epic.followup.util.AesUtil;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author : zx
 * @version V1.0
 */

@Controller
@RequestMapping("/wechat/patient")
public class WechatPatientController {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private WechatPatientService wechatPatientService;

    @RequestMapping(value = "/getOpendId", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getOpendId(@RequestBody JSONObject codeParams, HttpSession session) {

        Map<String, String> params = new HashMap<String, String>();
        params.put("secret", weChatConfig.getAppSecert());
        params.put("appid", weChatConfig.getAppID());
        params.put("js_code", codeParams.getString("code"));
        params.put("grant_type", weChatConfig.getGrantType());

        String result = null;
        try {
            result = get(weChatConfig.getUrl(), params, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // "openid": "oKR4L4051MQ_NJFp3T4ezysQw980",
        // "session_key": "rqDa1fGD7tH7aloGCrUekA=="
        JSONObject res = JSON.parseObject(result);

        JSONObject openidRes = new JSONObject();
        if (res.getString("openid") != null) {
            session.setAttribute("openid", res.getString("openid"));
            session.setAttribute("session_key", res.getString("session_key"));
            session.setMaxInactiveInterval(30 * 60);

            openidRes.put("errorCode", 200);
            openidRes.put("errorMsg", "获取openId成功");
            openidRes.put("sessionId", session.getId());
        } else {
            openidRes.put("errorCode", 502);
            openidRes.put("errorMsg", "获取openId失败");
        }

        return openidRes;
    }

    // 绑定电话实现一键登录
    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject autoLogin(@RequestBody JSONObject loginParams, HttpServletRequest req) {
        JSONObject result = new JSONObject();

        // 判断之前是否已经登录过
        HttpSession session = req.getSession();
        if (session.getAttribute("phone") != null) {
            // 之前的登录记录还在，直接返回
            result.put("errorCode", 200);
            result.put("errorMsg", "登录成功");
            result.put("sessionId", session.getId());
            return result;

        }

        // 需要session_key,iv,encrypData来解析电话实现微信一键登录
        try {
            String content = AesUtil.decrypt(loginParams.getString("encrypdata"),
                    (String) session.getAttribute("session_key"), loginParams.getString("ivdata"), "utf-8");
            result = JSON.parseObject(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = result.getString("phoneNumber");
        if (phone != null) {
            JSONObject isSuccess = wechatPatientService.wechatAutoLogin(phone);

            System.out.println("login : " + isSuccess);
            if (Boolean.TRUE.equals(isSuccess.getBoolean("label"))) {//存在直接登录
                // 登录成功
                session.setAttribute("phone", phone);
                session.setAttribute("id", isSuccess.getLong("id"));
                // wechatPatientBodyInformationService.
                // session.setAttribute(name, value);

                result.put("sessionId", session.getId());
                result.put("errorCode", 200);
                result.put("errorMsg", "登录成功");
            } else {//不存在直接注册登录
                System.out.println("用户：" + phone + " 未注册,正在注册");
                //数据库注册用户
                AppPatientModel u = new AppPatientModel();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                u.setCreateTime(df.format(new Date()));
                u.setOpenId((String) session.getAttribute("openid"));
                u.setTel(phone);
                wechatPatientService.savePatient(u);
                //查询插入记录的id存入session
                JSONObject pid = wechatPatientService.wechatAutoLogin(phone);
                session.setAttribute("phone", phone);
                session.setAttribute("id", pid.getLong("id"));

                result.put("sessionId", session.getId());
                result.put("errorCode", 200);
                result.put("errorMsg", "注册并登录成功");
            }
            return result;
        } else {
            result.put("errorCode", 502);
            result.put("errorMsg", "查询电话失败");
            return result;
        }

    }

    @RequestMapping(value = "/login/loginWithPasswd", method = RequestMethod.POST)
    @ResponseBody
    public DealMessageResponse loginWithPasswd(@RequestBody WechatLoginbyPasswordRequest userInfo) {

        return wechatPatientService.loginbyPassword(userInfo);
    }

    @RequestMapping(value = "/login/loginWithIdentifyCode", method = RequestMethod.POST)
    @ResponseBody
    public WechatLoginbyCodeResponse loginWithIdentifyCode(@RequestBody WechatLoginbyCodeRequest userInfo) {

        return wechatPatientService.loginbyCode(userInfo);
    }

    @RequestMapping(value = "/register/registerWithPasswd", method = RequestMethod.POST)
    @ResponseBody
    public DealMessageResponse registerWithPasswd(@RequestBody WechatRegisterRequest userInfo) {
        return wechatPatientService.register(userInfo);
    }

    @RequestMapping(value = "/getIdentifyCode", method = RequestMethod.POST)
    @ResponseBody
    public DealMessageResponse getCode(@RequestBody CodeRequest userInfo) {
        if (userInfo.getType() == 0) {// 登录
            return wechatPatientService.sendLoginCode(userInfo.getTel());
        } else if (userInfo.getType() == 1) {// 注册
            return wechatPatientService.sendRegisterCode(userInfo.getTel());
        } else if (userInfo.getType() == 2) {// 重置密码
            return wechatPatientService.sendResetPasswordCode(userInfo.getTel());
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/register/modifyPasswd", method = RequestMethod.POST)
    @ResponseBody
    public DealMessageResponse resetPassword(@RequestBody WechatRegisterRequest userInfo) {
        return wechatPatientService.resetPassword(userInfo);
    }

    @RequestMapping(value = "/user/setUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public DealMessageResponse setUserInfo(HttpSession session,@RequestBody WechatInformationRequest userInfo) {
        return wechatPatientService.setInformation(userInfo,(String)session.getAttribute("phone"));
    }

    @RequestMapping(value = "/user/getUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public WechatInformationResponse getUserInfo(HttpSession session) {
        return wechatPatientService.getInformation((String)session.getAttribute("phone"));
    }

}
